package com.rtwo.tio.common;

import org.tio.core.ChannelContext;
import org.tio.core.GroupContext;
import org.tio.core.exception.AioDecodeException;
import org.tio.core.intf.AioHandler;
import org.tio.core.intf.Packet;

import java.nio.ByteBuffer;

import static com.rtwo.tio.common.Common.HEADER_LENGTH;

/**
 * Created by bruce.zhou on 2018/6/29.
 */
public abstract class TioHandler implements AioHandler{

    @Override
    public Packet decode(ByteBuffer buffer, int i, int i1, int i2, ChannelContext channelContext) throws AioDecodeException {
        if(buffer.remaining()<HEADER_LENGTH){
            return null;
        }
        BasicPacket basicPacket = new BasicPacket();
        if(buffer!=null&&buffer.capacity()!=0){
            int length = buffer.getInt();
            byte type = buffer.get();
            byte[] body = new byte[length];
            buffer.get(body);
            basicPacket.setBody(body);
            basicPacket.setType(type);
            return basicPacket;
        }
        return basicPacket;
    }

    @Override
    public ByteBuffer encode(Packet packet, GroupContext groupContext, ChannelContext channelContext) {
        BasicPacket basicPacket = (BasicPacket)packet;
        byte type = basicPacket.getType();
        byte[] body = basicPacket.getBody();
        if(body!=null){
            int length = body.length;
            ByteBuffer byteBuffer = ByteBuffer.allocate(length+HEADER_LENGTH);
            byteBuffer.order(groupContext.getByteOrder());
            byteBuffer.putInt(length);
            byteBuffer.put(type);
            byteBuffer.put(body);
            return byteBuffer;
        }
        return null;
    }

    @Override
    public void handler(Packet packet, ChannelContext channelContext) throws Exception {

    }
}
